﻿@page "/search"

@inject IHttpService _httpService
@inject NavigationManager NavigationManager
@inject IDataCacheService _dataCacheService
@implements IDisposable

<CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="搜索" />


<div class="search-view">
    <MDCard Class="mb-3">
        <div style=" display: flex; justify-content: center; ">
            <div style=" display: flex;align-items: center;">
                <MTextField Placeholder="可以搜索哦~" TValue="string" @bind-Value="@InputModel.FilterText" OnKeyDown="OnKeyDown" Autofocus></MTextField>
                 <CnGalWebSite.Components.Buttons.MasaButton Text="搜索" Rounded IsAsync OnClick="OnSearchString" Icon="mdi-magnify" Class="ms-4" />
             </div>
         </div>
     </MDCard>
     <CnGalWebSite.Shared.MasaComponent.PC.Home.Search.ScreenCard OnChanged="()=>OnChanged()" Model="InputModel" />
     <div class="mt-3">

         @if (isReady == false)
        {
            <CnGalWebSite.Components.Progressings.ProgressingCard Page Fill />
        }
        else
        {

            @foreach (var item in DataModel.pagedResultDto.Data)
            {
                <div class="mb-3">
                    @if (item.entry != null)
                    {
                        <CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.EntryInforViewTip Model="item.entry"></CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.EntryInforViewTip>
                    }
                    else if (item.article != null)
                    {
                        <CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.ArticleInforViewTip Model="item.article"></CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.ArticleInforViewTip>
                    }
                    else if (item.periphery != null)
                    {
                        <CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.PeripheryInforViewTip Model="item.periphery"></CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.PeripheryInforViewTip>
                    }
                    else if (item.tag != null)
                    {
                        <CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.TagInforViewTip Model="item.tag"></CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.TagInforViewTip>
                    }
                    else if (item.video != null)
                    {
                        <CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.VideoInforViewTip Model="item.video"></CnGalWebSite.Shared.MasaComponent.Shared.Cards.Search.VideoInforViewTip>
                    }
                </div>
            }


            @if (DataModel.pagedResultDto.Data.Count == 0)
            {
                <NotFoundCard Fill>
                 <h1 class="text-center title-large">搜索不到呢......</h1>
                 <div class="text-center">不过你可以在这里<a href="/entries/establishentry">创建词条</a>或者<a href="/articles/createarticle">发布文章</a></div>
             </NotFoundCard>
            }
            else
            {
                @if (DataModel.pagedResultDto.TotalPages > 1)
                {
                    <CnGalWebSite.Components.Paginations.MasaPagination Value="@DataModel.pagedResultDto.CurrentPage" Length="@DataModel.pagedResultDto.TotalPages" ValueChanged="OnPageClick" />

                }

            }

        }
    </div>
</div>


@code {
    [SupplyParameterFromQuery]
    [Parameter]
    public string[] Types { get; set; }
    [SupplyParameterFromQuery]
    [Parameter]
    public string[] Times { get; set; }
    [SupplyParameterFromQuery]
    [Parameter]
    public string Text { get; set; }
    [SupplyParameterFromQuery]
    [Parameter]
    public string Sort { get; set; }

    [SupplyParameterFromQuery]
    [Parameter]
    public int Page { get; set; }

    SearchInputModel InputModel = new SearchInputModel();
    SearchViewModel DataModel = new SearchViewModel();
    bool isReady = false;

    private IEnumerable<int> PageItems => new int[] { 4, 8, 16, 30 };

    private IEnumerable<string> Items { get; set; } = new string[1] { "" };

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            NavigationManager.LocationChanged -= LocationChanged;
            NavigationManager.LocationChanged += LocationChanged;
            LocationChanged(null, null);
        }
    }

    public async void LocationChanged(object sender, LocationChangedEventArgs args)
    {
        if (NavigationManager.Uri.Contains("/search"))
        {
            try
            {
                SearchInputModel.TryParse(Types, Times, Text, Sort, Page, InputModel);

                //请求数据
                try
                {
                    var url = ToolHelper.WebApiPath + "api/home/search" + NavigationManager.Uri.Replace(NavigationManager.BaseUri, "").Replace("search", "");
                    DataModel = await _dataCacheService.SearchViewCatche.GetCache(url);

                }
                catch (Exception ex)
                {
                    await ErrorHandler.ProcessError(ex, "无法获取搜索结果");
                    DataModel = new SearchViewModel();

                }

                isReady = true;
                StateHasChanged();
            }
            catch
            {

            }
        }

    }

    protected override async Task OnInitializedAsync()
    {

    }



    public void OnChanged(int page = 1)
    {
        InputModel.CurrentPage = page;
        NavigationManager.NavigateTo("/search" + InputModel.ToQueryParameterString());


    }


    private void OnPageClick(int pageIndex)
    {
        if (isReady == false || DataModel.pagedResultDto.CurrentPage == pageIndex)
        {
            return;
        }
        OnChanged(pageIndex);
    }


    private void OnSearchString()
    {
        OnChanged();
    }


    private void OnSearchString(string text)
    {
        InputModel.FilterText = text;

        OnChanged();
    }

    private void OnKeyDown(KeyboardEventArgs e)
    {
        if (e.Code == "Enter" || e.Code == "NumpadEnter")
        {
            OnSearchString();
        }
    }

    #region 释放实例

    public void Dispose()
    {

        NavigationManager.LocationChanged -= LocationChanged;

        GC.SuppressFinalize(this);
    }
    #endregion
}
